<template>
  <div class="newsManage-container">
    <div class="newsManage-search">
      <span class="page-title">官网新闻列表</span>
      <el-input placeholder="请输入搜索内容" v-model="keyWords" class="input-with-select search-keyword">
        <el-select v-model="select" slot="prepend" placeholder="请选择">
          <el-option label="新闻标题" value="1"></el-option>
        </el-select>
      </el-input>
      <el-button type="primary" size="small" icon="el-icon-search" @click="searchNews">搜索</el-button>
      <el-button type="info" size="small" class="search-keyword-reset" plain @click="resetSearch">重置</el-button>
      <el-button type="success" size="small" icon="el-icon-plus" @click="handelAdd"
                 v-if="checkPermissionPoints(1) == 1">
        新增
      </el-button>
      <!--<el-button type="primary" size="small" icon="el-icon-edit" @click="toggleSelection(webNewsData)"-->
      <!--v-show="!checkBoxIcon">批量管理-->
      <!--</el-button>-->
      <!--<el-button type="info" size="small" plain @click="toggleSelection()" v-show="checkBoxIcon">取消批量管理</el-button>-->
      <!--<el-button type="danger" size="small" icon="el-icon-delete" class="button-position" v-if="checkBoxIcon"-->
      <!--@click="batchDel">删除选中-->
      <!--</el-button>-->
    </div>

    <div class="newsManage-table">
      <el-table ref="multipleTable" :data="webNewsData" border stripe fit v-loading="listLoading"
                :row-style="{height:'50px'}" :header-row-style="{height:'40px'}" @filter-change="filterChange"
                @selection-change="handleSelectionChange" :row-key="getRowKeys">
        <el-table-column type="selection" :reserve-selection="true" width="40" v-if="checkBoxIcon"></el-table-column>
        <el-table-column label="新闻标题" width="550">
          <template slot-scope="scope">
            {{scope.row.essayName}}
          </template>
        </el-table-column>
        <el-table-column label="封面" width="120">
          <template slot-scope="scope">
            <img v-viewer
                 v-lazy="scope.row.essayUrl?scope.row.essayUrl:require('../../../assets/common_images/placeholder-pic.png')"
                 style="object-fit: cover;width: 40px;height: 40px;border-radius: 2px"/>
          </template>
        </el-table-column>
        <el-table-column label="浏览量" width="100">
          <template slot-scope="scope">
            {{scope.row.view}}
          </template>
        </el-table-column>
        <el-table-column label="分类" width="120"
                         :filters="[{ text: '行业资讯', value:'行业资讯' }, { text: '政策法规', value: '政策法规' }, { text: '公司公告', value: '公司公告' },
                         { text: '公司动态', value: '公司动态' }]"
                         :filter-multiple="false" column-key="labelName"
                         filter-placement="bottom-end" prop="labelName">
          <template slot-scope="scope">
            <span>{{scope.row.labelName}}</span>
          </template>
        </el-table-column>

        <el-table-column label="生成时间" width="160">
          <template slot-scope="scope">
            <span v-if="scope.row.time">{{scope.row.time | formatTime}}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" min-width="200" fixed="right">
          <template slot-scope="{row}">
            <el-dropdown size="mini" :split-button="true" type="primary" @click="handleLook(row)"
                         v-if="checkPermissionPoints(3) == 1">查看
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click.native="handleEdit(row)" v-if="checkPermissionPoints(4) == 1">编辑
                </el-dropdown-item>
                <el-dropdown-item @click.native="handleDelete(row)" v-if="checkPermissionPoints(2) == 1">删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :type="1" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                  @pagination="getWebNewsList"/>
    </div>

    <!--查看-->
    <el-dialog title="详细信息" :visible.sync="dialogLookVisible" width="960px" class="newsManage-dialog look-dialog"
               top="11vh">
      <el-form label-width="140px" size="mini">
        <el-form-item label="新闻标题：">
          <span>{{webSiteNews.essayName}}</span>
        </el-form-item>
        <el-form-item label="新闻封面：">
          <img
            v-lazy="webSiteNews.essayUrl?webSiteNews.essayUrl:require('../../../assets/common_images/placeholder-pic.png')"
            style="object-fit: cover;width: 72px;height: 72px;border-radius: 2px"/>
        </el-form-item>
        <el-form-item label="新闻详情：">
          <el-input v-html="webSiteNews.essayDetails"></el-input>
        </el-form-item>
        <el-form-item label="浏览量：">
          <span>{{webSiteNews.view}}</span>
        </el-form-item>
        <el-form-item label="分类：">
          <span>{{webSiteNews.labelName}}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" style="width: 96px" @click="dialogLookVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <!--新增/编辑-->
    <el-dialog :title="textMap[dialogStatus]" :lock-scroll="true" :visible.sync="dialogEditVisible" width="960px"
               top="11vh"
               class="newsManage-dialog" @close="cancelNews">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="auto" size="mini">
        <el-form-item label="新闻标题：" prop="essayName">
          <el-input style="width: 640px;" placeholder="请输入新闻标题" :clearable="true"
                    v-model="ruleForm.essayName"></el-input>
        </el-form-item>
        <el-form-item label="新闻封面：" prop="essayUrl" ref="essayUrl">
          <span>只能上传jpg/png/jpeg文件，且不超过1M（建议尺寸320*320）</span>
          <el-upload :action="upload_qiniu_url" list-type="picture-card" :auto-upload="true"
                     :limit="1" accept="image/jpg,image/png,image/jpeg" :data="qiniuData" :file-list="fileList"
                     :before-upload="beforeImageUpload" :on-change="changeImage"
                     :on-exceed="handleExceed" :on-remove="handleRemove"
                     :http-request="upQiniu">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="新闻详情：" prop="essayDetails">
          <tinymce v-model="ruleForm.essayDetails" :height="300" ref="tinymceEditor"/>
        </el-form-item>
        <el-form-item label="浏览量：" prop="view">
          <el-input style="width: 640px;" placeholder="请输入浏览量" :clearable="true" v-model="ruleForm.view"></el-input>
        </el-form-item>
        <el-form-item label="分类:" prop="labelId">
          <el-select v-model="ruleForm.labelId" filterable placeholder="请选择">
            <el-option v-for="item in webSiteOptions" :key="item.id" :label="item.labelName"
                       :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="success" style="width: 96px" @click="saveNews" :loading="sendLoad">保存</el-button>
        <el-button size="small" style="width: 96px" @click="cancelNews">取消</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
  import Pagination from '@/components/Pagination';
  import {mapGetters} from 'vuex';
  import {permissionPoints} from '@/utils/permission';
  import {baseUrl} from "@/api/constant";
  import {formatDate} from "@/utils/index";
  import Tinymce from '@/components/Tinymce'
  import {getQiNiuUpToken} from "../../../api/user/user";
  import {
    addWebNews,
    deleteWebNews,
    getClassify,
    getInitWebNewsList,
    getWebNewsDetail,
    modifyWebNews
  } from "../../../api/service/service";

  export default {
    name: "webSiteNewsManage",
    computed: {
      ...mapGetters([
        'points'
      ])
    },
    components: {
      Pagination,
      Tinymce
    },
    data() {
      return {
        multipleSelection: [],
        checkBoxIcon: false,
        total: 0,
        listQuery: {
          page: 1,
          limit: 20,
          essayTitle: '',
          labelName: ''
        },
        keyWords: '',
        select: '1',
        listLoading: false,
        dialogType: 'edit',
        dialogLookVisible: false,
        dialogEditVisible: false,
        textMap: {
          update: '编辑',
          create: '新增'
        },
        dialogStatus: '',
        webNewsData: [],
        webSiteNews: {},
        ruleForm: {
          essayName: '',
          essayDetails: '',
          essayUrl: '',
          view: '',
          labelId: '',
          id: ''
        },
        rules: {
          essayName: [
            {required: true, message: '请输入新闻标题', trigger: 'blur'}
          ],
          essayDetails: [
            {required: true, message: '请输入新闻详情', trigger: 'blur'}
          ],
          essayUrl: [
            {required: true, message: '请输入新闻封面', trigger: 'blur'}
          ],
          view: [
            {required: true, message: '请输入浏览量', trigger: 'blur'}
          ],
          labelId: [
            {required: true, message: '请选择分类', trigger: 'change'}
          ]
        },
        webSiteOptions: [],
        upload_qiniu_url: "https://upload-z2.qiniup.com",
        upload_qiniu_addr: "http://pic.lanpin123.com/",
        qiniuData: {
          token: ""
        },
        fileList: [],
        sendLoad: false
      }
    },
    created() {
      this.getWebNewsList();
      getClassify(3).then((res) => {
        this.webSiteOptions = res.data;
      });

      getQiNiuUpToken().then((res) => {
        this.qiniuData.token = res.data;
      });
    },
    methods: {
      searchNews() {//搜索
        if (this.keyWords == '' || this.keyWords == undefined) {
          return this.$message.info({message: '请输入搜索内容', duration: 1000});
        }
        this.listQuery.essayTitle = '';
        if (this.select == 1) {
          this.listQuery.essayTitle = this.keyWords;
        }
        this.listQuery.page = 1;
        this.getWebNewsList();
      },
      resetSearch() {
        this.select = '1';
        this.keyWords = '';
        this.listQuery.essayTitle = '';
        this.listQuery.labelName = '';
        this.$refs.multipleTable.clearFilter();
        this.listQuery.page = 1;
        this.getWebNewsList();
      },
      getWebNewsList() {
        this.listLoading = true;
        getInitWebNewsList(this.listQuery).then((res) => {
          this.listLoading = false;
          let retObj = res;
          if (retObj.code == 0 && retObj.data != null) {
            const {items, totalRecord} = retObj.data;
            this.total = totalRecord;
            this.webNewsData = items;
          }
        }).catch(() => {
          this.listLoading = false;
        })
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      getRowKeys(row) {
        return row.id;
      },
      toggleSelection(rows) {
        if (rows) {
          this.checkBoxIcon = !this.checkBoxIcon;
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        } else {
          this.checkBoxIcon = false;
          this.$refs.multipleTable.clearSelection();
        }
      },
      batchDel() {//批量
        let row = this.commonSelection();
        if (row && Object.keys(row).length != 0) {
          this.handleDelete(row);
        }
      },
      commonSelection() {
        let row = {};
        let value = this.multipleSelection;
        if (value && value.length > 0) {
          let arr = [];
          value.forEach((item) => {
            arr.push(item.id);
          });
          row.id = arr.join(",");
        }
        return row;
      },
      filterChange(value) {//过滤
        this.listQuery.labelName = value.labelName;
        this.listQuery.page = 1;
        this.getWebNewsList();
      },
      checkPermissionPoints(type) {
        let pointObj = this.points.webSiteNewsManage;
        return permissionPoints(type, pointObj);
      },
      handelAdd() {
        this.dialogStatus = 'create';
        this.dialogEditVisible = true;
      },
      handleLook(row) {//详细信息
        this.dialogLookVisible = true;
        getWebNewsDetail(row.id).then((res) => {
          let retObj = res;
          if (retObj.code == 0 && retObj.data != null) {
            this.webSiteNews = retObj.data;
          }
        })
      },
      handleEdit(row) {//编辑
        this.dialogStatus = 'update';
        this.dialogEditVisible = true;
        getWebNewsDetail(row.id).then((res) => {
          let retObj = res;
          if (retObj.code == 0 && retObj.data != null) {
            this.ruleForm = retObj.data;
            this.fileList.push({'url': this.ruleForm.essayUrl});
            this.$refs.tinymceEditor.setContent(this.ruleForm.essayDetails);
          }
        })
      },
      handleExceed() {
        this.$notify.warning({
          title: '警告',
          message: '一次只能上传一张图片',
          duration: 2000
        });
      },
      beforeImageUpload(file) {
        const limitType = file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/jpeg';
        if (!limitType) {
          this.$notify.warning({
            title: '警告',
            message: '请上传格式为image/png,image/jpg,image/jpeg的图片'
          })
        }
        const limitSize = file.size / 1024 / 1024 / 1 < 1;
        if (!limitSize) {
          this.$notify.warning({
            title: '警告',
            message: '图片大小必须小于1M'
          })
        }
        return limitType && limitSize;
      },
      changeImage(file) {
        if (file) {
          this.ruleForm.essayUrl = file.name;
          this.$refs.ruleForm.clearValidate();
        }
      },
      handleRemove(file) {
        if (file) {
          this.ruleForm.essayUrl = '';
        }
      },
      commonImageUpload(req, callback) {
        const config = {
          headers: {'Content-Type': 'multipart/form-data'}
        };
        let fileType = '';
        if (req.file.type === 'image/jpg') {
          fileType = 'jpg'
        } else if (req.file.type === 'image/png') {
          fileType = 'png'
        } else if (req.file.type === 'image/jpeg') {
          fileType = 'jpeg'
        } else if (req.file.type === 'audio/mp4' || req.file.type === 'video/mp4') {
          fileType = 'mp4'
        }
        const key = `front-${formatDate(new Date(), 'yyyyMMddhhmmss')}${Math.floor(Math.random() * 100)}.${fileType}`;

        const fd = new FormData();
        fd.append('file', req.file);
        fd.append('token', this.qiniuData.token);
        fd.append('key', key);
        this.axios.post(this.upload_qiniu_url, fd, config).then(res => {
          callback(res);
        });
      },
      upQiniu(req) {
        this.commonImageUpload(req, (res) => {
          this.afterUploadPic(res);
        })
      },
      afterUploadPic(pic) {
        if (!pic.data.key) {
          this.$message.error({message: '新闻封面上传失败', duration: 2000});
          return;
        } else {
          this.ruleForm.essayUrl = this.upload_qiniu_addr + pic.data.key;
        }
      },
      handleDelete(row) {//删除
        this.$confirm('此操作将删除该新闻, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteWebNews(row.id).then((res) => {
            let retObj = res;
            if (retObj.code == 0 && retObj.data > 0) {
              this.$message.success({message: '删除成功', duration: 2000});
              this.getWebNewsList();
            } else {
              this.$message.error({message: '删除失败，请重试', duration: 2000});
            }
          })
        }).catch((err) => {
        });
      },
      saveNews() {
        if (this.dialogStatus == 'create') {
          this.$refs.ruleForm.validate((valid) => {
            if (valid) {
              this.sendLoad = true;
              addWebNews(this.ruleForm).then((res) => {//新增
                let retObj = res;
                this.sendLoad = false;
                if (retObj.code == 0 && retObj.data == 1) {
                  this.fileList = [];
                  this.$refs.ruleForm.resetFields();
                  this.$refs.tinymceEditor.setContent('');
                  this.dialogEditVisible = false;
                  this.$message.success({message: '新增成功', duration: 2000});
                  this.getWebNewsList();
                } else {
                  this.$message.error({message: '新增失败，请重试', duration: 2000});
                }
              }).catch(() => {
                this.sendLoad = false;
              })
            } else {
              return false;
            }
          });
        } else {
          this.$refs.ruleForm.validate((valid) => {
            if (valid) {
              this.sendLoad = true;
              modifyWebNews(this.ruleForm).then((res) => {//修改
                let retObj = res;
                this.sendLoad = false;
                if (retObj.code == 0 && retObj.data == 1) {
                  this.fileList = [];
                  this.$refs.ruleForm.resetFields();
                  this.$refs.tinymceEditor.setContent('');
                  this.dialogEditVisible = false;
                  this.$message.success({message: '修改成功', duration: 2000});
                  this.getWebNewsList();
                } else {
                  this.$message.error({message: '修改失败，请重试', duration: 2000});
                }
              }).catch(() => {
                this.sendLoad = false;
              })
            } else {
              return false;
            }
          });
        }
      },
      cancelNews() {
        this.dialogEditVisible = false;
        this.fileList = [];
        this.$refs.ruleForm.resetFields();
        this.$refs.tinymceEditor.setContent('');
      }
    },
    filters: {
      formatTime(time) {
        let date = new Date(time);
        return formatDate(date, 'yyyy-MM-dd hh:mm:ss');
      },
      filterLabelName(type) {
        if (type == 0) {
          return '处理中';
        } else if (type == 1) {
          return '审批通过';
        } else if (type == 2) {
          return '审批失败';
        } else if (type == 3) {
          return '已处理';
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  .newsManage-container {
    .newsManage-search {
      display: flex;
      align-items: center;
      width: 100%;
      height: 80px;
      .page-title {
        padding-left: 18px;
        min-width: 160px;
        text-align: left;
        font-size: 18px;
        font-weight: bold;
        color: rgba(61, 68, 77, 1);
      }
      .search-keyword {
        margin-right: 24px;
        width: 470px;
        > > > .el-select .el-input {
          width: 110px;
        }
        > > > .el-input-group__prepend {
          background-color: #fff;
        }
      }
      .search-keyword-reset {
        margin-right: 36px;
      }
      .excel-inout-box {
        margin-left: auto;
        margin-right: 18px;
      }
    }

    .newsManage-table {
      width: 98%;
      margin-left: 18px;
      > > > .el-table td, .el-table th {
        padding: 6px 0px;
      }
      > > > .el-table__header th {
        padding: 0;
        height: 30px;
        line-height: 30px;
      }
      > > > .el-table__fixed-right {
        height: 100% !important;
      }
      > > > .el-table__column-filter-trigger {
        line-height: 28px;
        i {
          font-size: 18px;
        }
      }
      > > > .el-table__row .cell {
        display: flex;
        align-items: center;
      }
      > > > .el-table__header .has-gutter .cell {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
    }

    .newsManage-dialog > > > .el-dialog .el-dialog__header {
      display: flex;
      align-items: center;
      height: 48px;
      background: #F7F8FA;
      padding: 0px 0px 0px 12px;
      position: fixed;
      width: 960px;
      z-index: 999;
      .el-dialog__headerbtn {
        top: 15px;
      }
    }
    .newsManage-dialog > > > .el-dialog {
      overflow-y: auto;
      height: 80%;
    }
    .newsManage-dialog > > > .el-dialog .el-dialog__body {
      margin-top: 48px;
    }
    .look-dialog > > > .el-form-item--mini.el-form-item, .el-form-item--small.el-form-item {
      margin-bottom: 0px;
    }
    .newsManage-dialog {
      font-size: 14px;
      color: #606266;
    }
    > > > .el-button {
      line-height: 1.2;
    }
  }
</style>
